package controller;

import com.alibaba.fastjson.JSON;
import jdk.internal.util.xml.impl.ReaderUTF8;
import model.Tree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import service.ITreeService;

import java.util.List;

@Controller
@RequestMapping("tree")
public class TreeController {
    @Autowired
    private ITreeService iTreeService;

    @RequestMapping("page")
    public ModelAndView page(Tree tree){
        List<Tree> list = iTreeService.list(null);
        ModelAndView mv = new ModelAndView();
        mv.addObject("list", list);
        mv.setViewName("manager/tree");
        return  mv;
    }

    @RequestMapping(value = "query" , produces = "text/html;charset=utf-8")
    @ResponseBody
    public String query(Tree tree){
        List<Tree> list = iTreeService.list(tree);
        JSON json = (JSON)JSON.toJSON(list);
        return json.toJSONString();
    }

    @RequestMapping("addPage")
    public ModelAndView addPage(String pId , String pName){
        ModelAndView mv = new ModelAndView();
        mv.addObject("pId", pId);
        mv.addObject("pName", pName);
        mv.setViewName("manager/sort_add");
        return  mv;
    }

    @RequestMapping(value = "add", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String add(Tree tree){
        int count = iTreeService.insert(tree);
        if(count <1){
            return  "0";
        }else {
            return "1";
        }
    }

    @RequestMapping("updatePage")
    public ModelAndView updatePage(String pId, String pName){
        ModelAndView mv = new ModelAndView();
        mv.addObject("pId", pId);
        mv.addObject("pName", pName);
        mv.setViewName("manager/sort_update");
        return  mv;
    }

    @RequestMapping(value = "update", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String  update(Tree tree){
        int count = iTreeService.update(tree);
        if(count <1){
            return "0";
        }else{
            return  "1";
        }
    }

    @RequestMapping(value = "delete", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String delete(Tree tree){
        int count = iTreeService.delete(tree);
        if(count <1 ){
            return  "0";
        }else{
            return "1";
        }
    }
}
